package com.touchalachs.game;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;

import com.touchalachs.core.Updatable;
import com.touchalachs.core.ui.TippableBasicUIElement;

public class Lachs extends TippableBasicUIElement implements Updatable {

	private static final float ANIMATION_DURATION = 0.3f;
	private final Bitmap fish;
	private final Calculator calc;
	private float currentPos;
	private final int initX;
	private final int screenWidth;
	/** 0 will start jumpanimation, >=1 indicates finished animation*/
	private float animationSec;
	
	public Lachs(int x, int y, int w, int h, Point screenSize, Calculator calc) {
		super(x, y, w, h, screenSize);
		this.fish = Bitmap.createScaledBitmap(Res.FISH, getDimension().width(), getDimension().height(), false);
		this.calc = calc;
		initX = x;
		screenWidth = screenSize.x;
		currentPos = 0;
		animationSec = ANIMATION_DURATION;
	}

	@Override
	public void draw(Canvas canvas) {
		Bitmap fishToDraw;
		if (animationSec < ANIMATION_DURATION){
			Matrix m = new Matrix();
			float angle=(float) Math.cos(animationSec*Math.PI/2/ANIMATION_DURATION);
			m.setRotate(-angle*8, 0, 0);
			m.preScale(1+angle*0.3f, 1+angle*0.3f);
			fishToDraw = Bitmap.createBitmap(fish, 0, 0, fish.getWidth(), fish.getHeight(), m, true);
		}else{
			fishToDraw = fish;
		}
		canvas.drawBitmap(fishToDraw, getDimension().left, getDimension().top, null);
	}

	@Override
	public boolean tipp(int x, int y) {
		calc.clickFish();
		animationSec = 0;
		return true;
	}

	@Override
	public void update(float deltaSec) {
		currentPos += 3 * deltaSec * (0.2 + Math.random());
		animationSec += deltaSec;
		Rect d = getDimension();
		int x = (int) ((initX + Math.sin(currentPos)*3)*screenWidth/100);
//		System.out.println("newX: "+x);
		d.set(x, d.top, x+d.width(), d.bottom);
	}
}
